<template>
  <div class="app-container" v-loading.fullscreen.lock="loading">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="身份证件号" prop="identyNo">
        <el-input v-model="queryParams.identyNo" placeholder="请输入身份证件号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="queryParams.studentId" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="考生号" prop="candidatesId">
        <el-input v-model="queryParams.candidatesId" placeholder="请输入考生号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="院系" prop="departments">
        <el-select v-model="form.departments" placeholder="请选院系" @keyup.enter.native="handleQuery">
          <el-option label="经管系" value="经管系"></el-option>
          <el-option label="机电系" value="机电系"></el-option>
          <el-option label="信息系" value="信息系"></el-option>
          <el-option label="中文系" value="中文系"></el-option>
          <el-option label="工商管理系" value="工商管理系"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['stureg:offlinecheckin:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['stureg:offlinecheckin:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['stureg:offlinecheckin:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="注册号" align="center" prop="registerId" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="联系电话" align="center" prop="telphone" />
      <el-table-column label="身份证号" align="center" prop="identyNo" />
      <el-table-column label="人脸头像" align="center" prop="faceImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.faceImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="是否报道" align="center" prop="isOffnetCheck" />
      <el-table-column label="线下报到时间" align="center" prop="checkDate" width="120" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="民族" align="center" prop="nation" />
      <el-table-column label="政治面貌" align="center" prop="politicsStatus" />
      <el-table-column label="身高" align="center" prop="height" />
      <el-table-column label="体重(kg)" align="center" prop="weight" />
      <el-table-column label="毕业院校" align="center" prop="graduateSchool" />
      <el-table-column label="学校所在地" align="center" prop="schoolAddress" />
      <el-table-column label="家庭联系人姓名" align="center" prop="familyContactName" />
      <el-table-column label="与本人关系" align="center" prop="relation" />
      <el-table-column label="家庭联系人电话" align="center" prop="familyContactPhone" />
      <el-table-column label="户籍所在地详细地址" align="center" prop="domicileAddress" />
      <el-table-column label="家庭现居地址" align="center" prop="homeAdress" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-camera" @click="photoUploadHandle(scope.row)"
            v-hasPermi="['system:info:edit']">验证头像</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:info:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改现场办理学生信息对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" readonly />
        </el-form-item>
        <el-form-item label="考生号" prop="candidatesId">
          <el-input v-model="form.candidatesId" placeholder="请输入考生号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="身份证件号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证件号" />
        </el-form-item>
        <el-form-item label="院系" prop="departments">
          <el-select v-model="form.departments" placeholder="请选院系">
            <el-option label="经管系" value="经管系"></el-option>
            <el-option label="机电系" value="机电系"></el-option>
            <el-option label="信息系" value="信息系"></el-option>
            <el-option label="中文系" value="中文系"></el-option>
            <el-option label="工商管理系" value="工商管理系"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->


    <!-- 验证头像 -->
    <el-dialog :visible.sync="dialogVisible" width="50%" :before-close="handleClose" style="margin-top: 0;">
      <div slot="title" class="titleTab">
        <div :class="activeName == 1 ? 'active' : 'inActive'" @click="tabChange(1)">
          摄像头抓拍
        </div>
      </div>

      <div class="contentTab">
        <div class="photo" v-if="activeName == 1">
          <div class="photo-top">
            <div class="left">
              <video style="width: 100%" id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight"
                autoPlay></video>
              <div style="text-align: center; padding-top: 20px">
                <el-button type="primary" @click="photographBtn" size="small">拍摄</el-button>
              </div>
            </div>
            <div class="right">
              <div class="exampleTwo">
                <canvas id="canvasCamera" class="canvas" :width="125" :height="160"></canvas>
                <canvas style="display: none" id="canvasCamera1" class="canvas" :width="330" :height="420"></canvas>
              </div>
            </div>
          </div>
          <div class="desc">
            <!-- <span>注意事项：</span>
            <span>1.图像大小建议尺寸为220*280像素:</span> -->
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">关 闭</el-button>
            <el-button type="primary" @click="submitHandle">验 证</el-button>
          </span>
        </div>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import {
  listOfflinecheckin,
  getOfflinecheckin,
  delOfflinecheckin,
  addOfflinecheckin,
  updateOfflinecheckin,
} from "@/api/stureg/offlinecheckin";

import { listInfo, updateInfo } from "@/api/stureg/intenetin";

import { validateImg } from "@/api/login";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Offlinecheckin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 现场办理学生信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        candidatesId: null,
        name: null,
        sex: null,
        phoneNumber: null,
        email: null,
        idCard: null,
        departments: null,
        handlingStatus: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      loading: false,

      os: true, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      imgSrc: "",
      activeName: "1", //弹窗的标题栏高亮
      videoWidth: 544,
      videoHeight: 418,
      dialogVisible: false,//弹窗的显隐
      imgSubSrc: "",

      valiForm: {
        faceImage: "",
        identyNo: ""
      },

      selectedItem: {

      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询现场办理学生信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentId: null,
        candidatesId: null,
        name: null,
        sex: null,
        phoneNumber: null,
        email: null,
        idCard: null,
        departments: null,
        handlingStatus: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加现场办理学生信息";
    // },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids;
    //   getOfflinecheckin(id).then((response) => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改现场办理学生信息";
    //   });
    // },
    // /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate((valid) => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateOfflinecheckin(this.form).then((response) => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addOfflinecheckin(this.form).then((response) => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    // /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal
    //     .confirm('是否确认删除现场办理学生信息编号为"' + ids + '"的数据项？')
    //     .then(function () {
    //       return delOfflinecheckin(ids);
    //     })
    //     .then(() => {
    //       this.getList();
    //       this.$modal.msgSuccess("删除成功");
    //     })
    //     .catch(() => { });
    // },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "stureg/offlinecheckin/export",
        {
          ...this.queryParams,
        },
        `offlinecheckin_${new Date().getTime()}.xlsx`
      );
    },

    // 点击图片上传弹窗显示
    photoUploadHandle(row) {
      this.selectedItem = { ...row };
      this.valiForm.identyNo = row.identyNo;
      this.activeName = 1;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.resetBtn();
        this.openCamera();
      });
    },
    // 调用摄像头权限
    openCamera() {
      console.log("调取权限");
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisCancas1 = document.getElementById("canvasCamera1");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisContext1 = this.thisCancas1.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: 220, // _this.videoWidth,
            height: 280, // _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    // 拍照按钮
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(this.thisVideo, 0, 0, 125, 160);
      // 获取图片base64链接预览
      this.imgSrc = this.thisCancas.toDataURL("image/jpeg");
    },
    // 清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    // 重置画布
    resetBtn() {
      this.clearCanvas("canvasCamera");
    },
    // 关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
    //关闭弹窗
    handleClose() {
      this.dialogVisible = false;

      if (this.activeName == 1) {
        this.activeName = 2;
        this.resetBtn();
        this.stopCamera();
        this.os = false;
        this.dialogVisible = false;
      } else {
        this.stopCamera();
        this.dialogVisible = false;
      }
    },
    //点击 摄像头 上传  验证
    submitHandle() {
      this.loading = true;
      //this.dialogVisible = false;
      let file1 = this.base64ToFile(this.imgSrc, this.selectedItem.userName + "现场报到头像.jpg", "image/jpg");
      const formData = new FormData();
      formData.append("file", file1);

      fetch(process.env.VUE_APP_BASE_API + "/common/upload", {
        method: "POST",
        body: formData
      })
        .then((response) => response.json())
        .then(async (json) => {

          if (json.code == 200) {
            this.valiForm.faceImage = json.fileName;
            let isVali = await this.vali();
            if (isVali == "true") {
              this.selectedItem.isOffnetCheck = "是";
              this.selectedItem.checkDate = parseTime(new Date().toLocaleDateString(), '{y}-{m}-{d}')
              updateInfo(this.selectedItem).then(response => {
                this.$modal.msgSuccess("报到成功");

                this.getList();
                this.dialogVisible = false;
              });
            }else{
              this.$message.error("头像验证失败,请重新拍照验证");
              this.loading = false;
              return;
            }
            this.loading = false;
          } else {
            this.$message.error("上传图片出现错误" + json.msg);
            this.loading = false;
          }
        })
        .catch(error => {
          // 处理上传错误
          this.loading = false;
          this.$message.error("出错啦，请联系管理人员");
        });

    },
    base64ToFile(base64, filename, contentType) {
      var arr = base64.split(',')  //去掉base64格式图片的头部
      var bstr = atob(arr[1])   //atob()方法将数据解码
      var leng = bstr.length
      var u8arr = new Uint8Array(leng)
      while (leng--) {
        u8arr[leng] = bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
      }
      return new File([u8arr], filename, { type: contentType })
    },

    //验证头像
    async vali() {
      const res = await validateImg(this.valiForm);
      return res.msg.toString();
    },

  },
};
</script>
